package com.javablog.redis.demo.lock;


import com.javablog.redis.demo.service.KeyValueCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author ycd0075
 */


@Component
public class LockRepository {

    @Autowired
    private KeyValueCacheService redisService;

    private static final String RELEASE_SUCCESS = "1";

    /**
     * 获取分布式锁
     *
     * @param lockKey    锁唯一标识
     * @param requestId  客户端对象id，解锁时需要验证
     * @param expireTime 过期时间，防止死锁，单位毫秒
     * @return true 获取成功
     */
    public boolean tryLock(String lockKey, String requestId, long expireTime) {

        try {
            return redisService.setNx(lockKey, requestId, expireTime);
        } catch (Exception e) {
            //log.error("加锁失败", e);
            releaseLock(lockKey, requestId);
        }
        return false;
    }


    /**
     * 释放分布式锁
     *
     * @param lockKey   锁唯一标识
     * @param requestId 客户端对象id
     * @return true      获取成功
     */
    public boolean releaseLock(String lockKey, String requestId) {
        try {
            List<String> keys = Arrays.asList(lockKey);
            List<String> args = Arrays.asList(requestId);
            CacheResult res = redisService.evalScript("lua/DistributedLock.lua", keys, args);
            return Objects.equals(res.getRs(), RELEASE_SUCCESS);

        } catch (RuntimeException e) {
            // log.error("解锁失败,key:{}", e.getMessage());
        }
        return false;
    }
}
